package com.huaxia.day14.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockByReentrantLoack {
    private static final Lock lock = new ReentrantLock(true);
    public static void main(String[] args) throws Exception {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
//                    add();
                    tryAdd();
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
//                    add();
                    tryAdd();
                }
            }
        };
        t1.start();
        t2.start();

        Thread.sleep(2000);
        System.out.println(Const.num);
    }

    static class Const {
        public static int num = 0;
    }

    public static  void add() {
        lock.lock();
        try{
            Const.num++;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static  void tryAdd() {
        try{
            boolean getLock =lock.tryLock(1, TimeUnit.MINUTES);
            if (getLock){
                Const.num++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
